﻿using Serilog;
using System;
using System.Text;
using YWM.Common.Exceptions;
using YWM.Exceptions;

namespace PLC.Core.Exceptions
{
    /// <summary>
    /// 异常处理类
    /// </summary>
    public class ExceptionHandler : IExceptionHandler
    {
        /// <summary>
        /// 日志记录
        /// </summary>
        private readonly ILogger _logger;

        public ExceptionHandler(ILogger logger)
        {
            _logger = logger;
        }

        /// <summary>
        /// 处理异常
        /// </summary>
        /// <param name="exception">异常对象</param>
        /// <param name="infoName">信息名</param>
        /// <param name="feAction">友好异常处理委托</param>
        public void OnHandleException(Exception exception, string infoName, Action<FriendlyException> feAction = null)
        {
            try
            {
                if (exception is FriendlyException)
                {
                    FriendlyException fe = (FriendlyException)exception;
                    if (fe.OriginException != null)
                    {
                        _logger.Error(fe.OriginException, ExceptionToString(infoName));
                    }
                    feAction(fe);
                }
                else
                {
                    _logger.Error(exception, ExceptionToString(infoName));
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, ExceptionToString($"{infoName}处理函数"));
            }
        }

        /// <summary>
        /// 提取异常信息
        /// </summary>
        private string ExceptionToString(string info)
        {
            StringBuilder str = new StringBuilder($"{DateTime.Now}, {info}发生了一个错误！{Environment.NewLine}");
            return str.ToString();
        }
    }
}
